package com.liang.servicefeign;

import feign.hystrix.FallbackFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Feign程序
 *
 * @author liangyehao
 * @date 2021/03/18
 */
@SpringBootApplication
@RestController
@EnableFeignClients
public class FeignApp {
    public static void main(String[] args) {
        SpringApplication.run(FeignApp.class,args);
    }

    @Autowired
    HiServiceInterface hiServiceInterface;

    @RequestMapping("/triggerFeignHi")
    public String hi(@RequestParam String name){
        return hiServiceInterface.hi(name);
    }

}

//@FeignClient(value = "SERVICE-HI",fallback = HiServiceFallback.class)
//@FeignClient(value = "SERVICE-HI",url="http://localhost:8080",fallbackFactory = HiServiceFallbackFactory.class)
@FeignClient(value = "SERVICE-HI",fallbackFactory = HiServiceFallbackFactory.class)
interface HiServiceInterface{
    @RequestMapping("/hi")
    String hi(@RequestParam String name);
}

/**
 * 服务后备工厂
 * 2.fallbackFactory，可以捕捉到异常
 *
 * @author liangyehao
 * @date 2021/03/18
 */
@Component // 不加@Component注解无法识别
class HiServiceFallbackFactory implements FallbackFactory<HiServiceInterface>{

    @Override
    public HiServiceInterface create(Throwable throwable) {
        return new HiServiceInterface() {
            @Override
            public String hi(String name) {
                return "HiServiceFallbackFactory,"+name+". exception:"+throwable.getMessage();
            }
        };
    }
}


/**
 * 服务回退
 * 1. fallback属性回退，没法捕捉异常
 *
 * @author liangyehao
 * @date 2021/03/18
 */
@Component // 不加@Component注解无法识别
class HiServiceFallback implements HiServiceInterface{

    @Override
    public String hi(String name) {
        return "HiServiceFallback,"+name;
    }

}